package com.internetCafes.spms.common.aspect;

import com.google.gson.Gson;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.utils.HttpContextUtils;
import com.internetCafes.spms.core.utils.IPUtils;
import com.internetCafes.spms.web.sys.form.SysLoginForm;
import com.internetCafes.spms.web.sys.model.LogInfo;
import com.internetCafes.spms.web.sys.model.UserInfo;
import com.internetCafes.spms.web.sys.service.LogInfoService;
import com.sms.common.util.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * 系统日志，切面处理类
 *
 * @author Sunny
 * @email rekeeper2011@hotmail.com
 * @date 2017年3月8日 上午11:07:35
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {
	@Autowired
	private LogInfoService logInfoService;

	@Pointcut("@annotation(com.internetCafes.spms.core.annotation.SysLog)")
	public void logPointCut() {

	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;

		//保存日志
		saveSysLog(point, time);

		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		LogInfo sysLog = new LogInfo();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = joinPoint.getArgs();
		try{
			String params = new Gson().toJson(args[0]);
			// 参数长度判断，超过5000之后截取前5000
			if (params.length() > 5000) {
				params= params.substring(0, 5000);
			}
			sysLog.setParams(params);
		}catch (Exception e){
			log.error("接口请求参数解析失败！");
		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));

		//用户名
		String username;
		Long tenantId;
		if (args[0] instanceof SysLoginForm ){
			username = ((SysLoginForm) args[0]).getUsername();
			tenantId = ((SysLoginForm) args[0]).getTenantId();
		}else {
            username = ((UserInfo) SecurityUtils.getSubject().getPrincipal()).getName();
			tenantId = ((UserInfo) SecurityUtils.getSubject().getPrincipal()).getDeptId();
        }
		sysLog.setUsername(username);
		if (ObjectUtil.isNull(tenantId)) {
			tenantId = 0L;
		}

		sysLog.setTime(time);
		sysLog.setCreateDate(new Date());
		sysLog.setTenantId(tenantId);
		//保存系统日志
		logInfoService.save(sysLog);
	}
}
